package com.robinmouren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.robinmouren.constant.MessageConstant;
import com.robinmouren.constant.NumberConstant;
import com.robinmouren.constant.OrderConstant;
import com.robinmouren.constant.StatusConstant;
import com.robinmouren.dto.QuotationPageDto;
import com.robinmouren.dto.TransportCreateDto;
import com.robinmouren.entity.OrderInfo;
import com.robinmouren.entity.TransportRoute;
import com.robinmouren.exception.ErrorTimeException;
import com.robinmouren.mapper.TransportRouteMapper;
import com.robinmouren.service.ITransportRouteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.robinmouren.utils.DateUtils;
import com.robinmouren.utils.StringUtils;
import com.robinmouren.vo.TransportRouteVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 路线表，记录运输的所有路线以及单价、有效期 服务实现类
 * </p>
 *
 * @author Robinmouren
 * @since 2024-05-18
 */
@Service
public class TransportRouteServiceImpl extends ServiceImpl<TransportRouteMapper, TransportRoute> implements ITransportRouteService {


    /**
     * 司机创建运输路线
     *
     * @param dto
     */
    @Override
    public void create(TransportCreateDto dto) {
        Long id = Long.valueOf(dto.getId());
        // 判断添加的路线是否重复
        String origin = dto.getOrigin();
        String destination = dto.getDestination();


        List<TransportRoute> list = this.list(new LambdaQueryWrapper<TransportRoute>().eq(TransportRoute::getDriverId, id));
        list.forEach(item -> {
            String dataOrigin = item.getOriginPlace();
            String dataDestination = item.getDestination();
            // 判断路线名称是否重复
            if (origin.equals(dataOrigin) && destination.equals(dataDestination)) {
                // 若重复 判断时间是否过期
                LocalDateTime startTime = dto.getStartTime();
                LocalDateTime endTime = dto.getEndTime();
                LocalDateTime validEndTime = item.getValidEndTime();
                LocalDateTime validStartTime = item.getValidStartTime();

                if (DateUtils.ifTimeHasChengHsien(startTime, endTime, validStartTime, validEndTime)) {
                    throw new ErrorTimeException(MessageConstant.ROUTER_TIME_NOT_OVERDUE);
                }
            }
        });

        TransportRoute build = TransportRoute.builder()
                .driverId(id)
                .originPlace(dto.getOrigin())
                .destination(dto.getDestination())
                .validEndTime(dto.getEndTime())
                .validStartTime(dto.getStartTime())
                .status(StatusConstant.ENABLE)
                .fee(dto.getFee())
                .unit(dto.getUnit())
                .build();

        this.save(build);
    }


    /**
     * 司机运输路线分页查询
     *
     * @param pageDto
     * @return
     */
    @Override
    public Page<TransportRouteVo> transportPage(QuotationPageDto pageDto) {

        LocalDateTime startTime = pageDto.getStartTime();
        LocalDateTime endTime = pageDto.getEndTime();
        String input = pageDto.getInput();
        int status = pageDto.getStatus();
        String id = pageDto.getId();

        // 获取选项框选项
        SFunction<TransportRoute, ?> function1 = OrderConstant.TRANSPORT_ROUTE_MAP.get(pageDto.getValue1());
        SFunction<TransportRoute, ?> function2 = OrderConstant.TRANSPORT_ROUTE_MAP.get(pageDto.getValue2());


        Page<TransportRoute> routePage = new Page<>(pageDto.getPage(), pageDto.getPageSize());
        this.page(routePage,
                new LambdaQueryWrapper<TransportRoute>()
                        .like(!Objects.equals(input, NumberConstant.NULL_STRING), function1, input)
                        .gt(startTime != null, function2, startTime)
                        .lt(endTime != null, function2, endTime)
                        .eq(status != NumberConstant.MINUS_ONE, TransportRoute::getStatus, status)
                        .and(wrapper -> {
                            wrapper.eq(TransportRoute::getDriverId,id);
                        })
                        .orderByDesc(TransportRoute::getCreateTime)
        );

        Page<TransportRouteVo> page = new Page<>();
        BeanUtils.copyProperties(routePage,page,"records");

        List<TransportRoute> records = routePage.getRecords();
        List<TransportRouteVo> collect = records.stream().map(item -> {
            TransportRouteVo transportRouteVo = new TransportRouteVo();
            BeanUtils.copyProperties(item, transportRouteVo);

            transportRouteVo.setId(item.getId().toString());
            transportRouteVo.setPrice(item.getFee() + item.getUnit());
            return transportRouteVo;
        }).collect(Collectors.toList());

        page.setRecords(collect);
        return page;
    }
}
